﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PSTaskDialog;
using smx.Properties;
namespace smx
{
    public partial class transactions : Form
    {
        public transactions()
        {
            InitializeComponent();
        }

        //----------------------------------------------------------------------------------------------------------------------------
        //loads the customers, suppliers, components and products into the combos
        //----------------------------------------------------------------------------------------------------------------------------
        private void transactions_Load(object sender, EventArgs e)
        {
            getCustomers();
            getProducts();
            getSuppliers();
        }

        //----------------------------------------------------------------------------------------------------------------------------
        #region selection methods
        //----------------------------------------------------------------------------------------------------------------------------

        //----------------------------------------------------------------------------------------------------------------------------
        //customer load
        //----------------------------------------------------------------------------------------------------------------------------
        private void getCustomers()
        {
            stockmanagerexpressEntities data = new stockmanagerexpressEntities();
            try
            {

                var q = from c in data.customers
                        select new 
                        {
                            c.id,
                            c.lastname
                        };
                custCombo.DisplayMember = "lastname";
                custCombo.ValueMember = "id";
                custCombo.DataSource = q;
            }
            catch (Exception err)
            {
                cTaskDialog.MessageBox(this, "Error in Code",
                         "There was an error!",
                         "There was an error in attempting to get the customers,  there could be many reasons. IF the problem persists please let us know, for more information view the details" + err.Message,
                         err.ToString(), "Database error", "", eTaskDialogButtons.OK, eSysIcons.Error, eSysIcons.Error);
            }
        }
        //----------------------------------------------------------------------------------------------------------------------------
        //product load
        //----------------------------------------------------------------------------------------------------------------------------
        private void getProducts()
        {
            stockmanagerexpressEntities data = new stockmanagerexpressEntities();
            try
            {

                var q = from c in data.products
                        select new
                        {
                            c.id,
                            c.name
                        };
                prodCombo.DisplayMember = "name";
                prodCombo.ValueMember = "id";
                prodCombo.DataSource = q;
            }
            catch (Exception err)
            {
                cTaskDialog.MessageBox(this, "Error in Code",
                         "There was an error!",
                         "There was an error in attempting to get the products,  there could be many reasons. IF the problem persists please let us know, for more information view the details" + err.Message,
                         err.ToString(), "Database error", "", eTaskDialogButtons.OK, eSysIcons.Error, eSysIcons.Error);
            }
        }

        //----------------------------------------------------------------------------------------------------------------------------
        //supplier load
        //----------------------------------------------------------------------------------------------------------------------------
        private void getSuppliers()
        {
            stockmanagerexpressEntities data = new stockmanagerexpressEntities();

            var q = from p in data.suppliers
                    select new
                    {
                        p.id,
                        p.company
                    };
            suppCombo.DisplayMember = "company";
            suppCombo.ValueMember = "id";
            suppCombo.DataSource = q;

        }

        //----------------------------------------------------------------------------------------------------------------------------
        //allow the components combo box only to show the components that this supplier can show
        //----------------------------------------------------------------------------------------------------------------------------
        private void suppCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            getComps();
        }

        //----------------------------------------------------------------------------------------------------------------------------
        //components load
        //----------------------------------------------------------------------------------------------------------------------------
        private void getComps()
        {
            
            stockmanagerexpressEntities data = new stockmanagerexpressEntities();

            long sid = Convert.ToInt64(suppCombo.SelectedValue);
            var q = from c in data.components
                    where c.supplier_id == sid
                    select new
                    {
                        c.id,
                        c.name,
                    };

            compCombo.DisplayMember = "name";
            compCombo.ValueMember = "id";
            compCombo.DataSource = q;

        }

        #endregion

        //----------------------------------------------------------------------------------------------------------------------------
        #region saving a sale
        //----------------------------------------------------------------------------------------------------------------------------




       

        //----------------------------------------------------------------------------------------------------------------------------
        //saving a sale to the database
        //----------------------------------------------------------------------------------------------------------------------------
        private void saveSaleBtn_Click(object sender, EventArgs e)
        {
            try
            {
                using (stockmanagerexpressEntities data = new stockmanagerexpressEntities())
                {
                    //the products id
                    long prodid = Convert.ToInt64(prodCombo.SelectedValue);
                    //how many we wish to sell
                    long saleqty = Convert.ToInt64(saleQtyTxt.Text);
                    //get the components for this product
                    var q = from c in data.compsforprods
                            where c.prodid == prodid
                            select c;

                    //go through the components and take away the value of qty
                    foreach (compsforprod c in q)
                    {
                        //the amount of stock to take away
                        long result = (long)c.qtyneeded * saleqty;
                        //get the component
                        var compqty = (from co in data.components
                                       where co.id == c.id
                                       select co).First();
                        //takeaway the total amount of components from the qty
                        long takeaway = compqty.qtyinstock - result;
                        //check if this leaves the consumer with less components than they have if so cancel this method
                        if (takeaway < 0)
                        {
                            cTaskDialog.MessageBox(this,
                 "User Error",
                 "You cannot sell this product as you do not have enough components",
                 "If you wish to sell this item you need to buy more stock items that are not enough " + c.name.ToString(),
                 eTaskDialogButtons.OK,
                 eSysIcons.Error);
                            return;
                        }
                        //if not the we save the new value to the database
                        compqty.qtyinstock = takeaway;
                        data.SaveChanges();
                    }
                    using (stockmanagerexpressEntities data1 = new stockmanagerexpressEntities())
                    {


                        //and then we can log the sale
                        //by generating a key
                        keyGen gen = new keyGen();
                        long newsaleid = gen.generateId();
                        //getting the customer details
                        long custid = Convert.ToInt64(custCombo.SelectedValue);
                        sale s = new sale();
                        //setting the values
                        s.id = newsaleid;
                        s.description = saleDesTxt.Text;
                        s.qty = saleqty;
                        s.product_id = prodid;
                        s.customer_id = custid;
                        //adding and saving the database 
                        data1.AddTosales(s);
                        data1.SaveChanges();


                    }
                }
                AddMoney();
                //reset the textboxes and show a confirmation on the status label
                saleDesTxt.Text = "";
                saleQtyTxt.Text = "";
                statusLbl.Text = "Saved the sale";
            }
            catch (Exception err)
            {
                cTaskDialog.MessageBox(this, "Error in Code",
                  "There was an error!",
                  "There was an error in attempting to save the sale,  there could be many reasons. IF the problem persists please let us know, for more information view the details" + err.Message,
                  err.ToString(), "Database error", "", eTaskDialogButtons.OK, eSysIcons.Error, eSysIcons.Error);
            }
        }

        //----------------------------------------------------------------------------------------------------------------------------
        //add the money to the total from the sale
        //----------------------------------------------------------------------------------------------------------------------------
        private void AddMoney()
        {
            try
            {
                using (stockmanagerexpressEntities data = new stockmanagerexpressEntities())
                {
                    long pid = Convert.ToInt64(prodCombo.SelectedValue);
                    var price = (from p in data.products
                                 where p.id == pid
                                 select p.value).First();
                    long saleqty = Convert.ToInt64(saleQtyTxt.Text);
                    decimal result = price * saleqty;
                    decimal newfinance  = Settings.Default.finance + result;
                    Settings.Default.finance = newfinance;
                    Settings.Default.Save();

                }

            }
            catch (Exception err)
            {
                cTaskDialog.MessageBox(this, "Error in Code",
           "There was an error!",
           "There was an error in attempting to edit the finances,  there could be many reasons. IF the problem persists please let us know, for more information view the details" + err.Message,
           err.ToString(), "Database error", "", eTaskDialogButtons.OK, eSysIcons.Error, eSysIcons.Error);
            }

        }



        #endregion

        //----------------------------------------------------------------------------------------------------------------------------
        #region add an  expense
        //----------------------------------------------------------------------------------------------------------------------------

        //----------------------------------------------------------------------------------------------------------------------------
        //the main button click event that handles adding new expense
        //----------------------------------------------------------------------------------------------------------------------------
        private void exSaveBtn_Click(object sender, EventArgs e)
        {
            try
            {
                stockmanagerexpressEntities data = new stockmanagerexpressEntities();
                keyGen gen = new keyGen();
                long eid = gen.generateId();
                expens ex = new expens();
                long compid = Convert.ToInt64(compCombo.SelectedValue);
                long suppid = Convert.ToInt64(suppCombo.SelectedValue);
                ex.id = eid;
                ex.description = expdescTxt.Text;
                ex.component_id = compid;
                ex.supplier_id = suppid;
                ex.quantity = Convert.ToInt64(expqtyTxt.Text);
                data.AddToexpenses(ex);
                data.SaveChanges();

                takeawayMoney();
                addStock();

                statusLbl.Text = "Saved new expense";
            }
            catch (Exception err)
            {
                cTaskDialog.MessageBox(this, "Error in Code",
  "There was an error!",
  "There was an error in attempting to add an expense,  there could be many reasons. IF the problem persists please let us know, for more information view the details" + err.Message,
  err.ToString(), "Database error", "", eTaskDialogButtons.OK, eSysIcons.Error, eSysIcons.Error);
            }
        }

        //----------------------------------------------------------------------------------------------------------------------------
        //takes away the money from the finance setting
        //----------------------------------------------------------------------------------------------------------------------------
        private void takeawayMoney()
        {
            using (stockmanagerexpressEntities data = new stockmanagerexpressEntities())
            {
                long cid = Convert.ToInt64(compCombo.SelectedValue);
                var price = (from c in data.components
                             where c.id == cid
                             select c.value).First();
                long expqty = Convert.ToInt64(expqtyTxt.Text);
                decimal result = expqty * price;
                decimal newfinance = Settings.Default.finance - result;
                Settings.Default.finance = newfinance;
                Settings.Default.Save();
            }

        }

        //----------------------------------------------------------------------------------------------------------------------------
        //adds the stock to the component bought
        //----------------------------------------------------------------------------------------------------------------------------
        private void addStock()
        {
            stockmanagerexpressEntities data = new stockmanagerexpressEntities();
            long cid = Convert.ToInt64(compCombo.SelectedValue);

            var q = (from c in data.components
                     where c.id == cid
                     select c).First();
            long qty = (long)q.qtyinstock;
            long exqty = Convert.ToInt64(expqtyTxt.Text);
            long newqty = qty + exqty;

            q.qtyinstock = newqty;
            data.SaveChanges();
        }

        #endregion

        //----------------------------------------------------------------------------------------------------------------------------
        //closes the form if the user agrees
        //----------------------------------------------------------------------------------------------------------------------------
        private void finishedBtn_Click(object sender, EventArgs e)
        {
            if (
             cTaskDialog.MessageBox(this,
                 "Confirmation",
                 "Are you finished?",
                 "If you are finished click yes or else to carry on click no. You can always return here later if you have more sales or expenses",
                 eTaskDialogButtons.YesNo,
                 eSysIcons.Question) == DialogResult.Yes)
            {
                this.Close();
            }
        }







    }
}
